package org.i1510.common.controller;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

import net.sf.json.JSONArray;

import org.i1510.common.bean.PageBean;
import org.i1510.common.dao.ISysDataDao;
import org.i1510.common.po.SysData;
import org.i1510.common.po.SysUser;
import org.i1510.common.service.ISysDataService;
import org.i1510.common.utils.KBProperties;
import org.i1510.common.utils.PrintWriterUtils;
import org.i1510.common.utils.StringUtils;
import org.i1510.common.utils.UserUtils;
import org.i1510.common.utils.encryption.Md5;
import org.i1510.common.utils.web.ResultMapper;
import org.i1510.common.utils.web.WebUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
@RequestMapping(value = "/admin/sysData")
public class SysDataController {
    private static final Logger logger = LoggerFactory.getLogger(SysDataController.class);
    @Autowired
    private ISysDataService iSysDataService;
    @Autowired
    private ISysDataDao iSysDataDao;
    
    private ResultMapper mapper;
    /**
     *@Author Rambo
     *@Desc：获取树结构 仅用于 fdParentCode为唯一的编码
     *@param sysData
     *@param errors
     *@return TODO
     *@Version  SysDataController.java,v 1.1 2013-11-15 下午4:20:56 
     */
     @RequestMapping(value = "/findTree", method =  {RequestMethod.POST, RequestMethod.GET })
     @ResponseBody
     public String findTree(HttpServletRequest request,HttpServletResponse response,@Valid @ModelAttribute("sysData") SysData sysData,@Valid @ModelAttribute("fdParentCode") String fdParentCode,BindingResult errors) {
 	
 		
    	Map conditions = new HashMap();
    	//通过父编码查找下级数据
    	if(!StringUtils.isStringEmpty(fdParentCode)){
    		SysData sd = iSysDataService.findByfdCode(fdParentCode);
    		if(null != sd){
    			conditions.put("fdParentId", sd.getDocId());
    		}
    	}
		List  list = iSysDataService.getAll(sysData, conditions);
		JSONArray jsonArray = new JSONArray();
		if (list.size() > 0) {
			jsonArray = JSONArray.fromObject(list);
		}
		PrintWriterUtils write = new PrintWriterUtils();
		write.sendPrintWriterUtils(response, jsonArray.toString(), "json");
		return null;
     }
     @RequestMapping(value = "/listExt", method = {RequestMethod.POST, RequestMethod.GET } )
 	@ResponseBody
 	public String listExt(@Valid @ModelAttribute("start") String start,@Valid @ModelAttribute("limit") String limit,@Valid @ModelAttribute("fdParentCode") String fdParentCode,@Valid @ModelAttribute("sysData") SysData sysData,@Valid @ModelAttribute("pageBean") PageBean pageBean,BindingResult errors) {
 		ResultMapper mapperRtn = ResultMapper.generateFailure();
 		if(errors.hasErrors()){			
 			mapperRtn = WebUtils.getMapper4Errors(errors);
 		}else{
 			Map conditions = new HashMap();
 	    	//通过父编码查找下级数据
 	    	if(!StringUtils.isStringEmpty(fdParentCode)){//仅用于 fdParentCode为唯一的编码
 	    		SysData sd = iSysDataService.findByfdCode(fdParentCode);
 	    		if(null != sd){
 	    			conditions.put("fdParentId", sd.getDocId());
 	    		}
 	    	}
 			if(!"".equals(start) && !"".equals(limit)){
 				pageBean.setIntPageIndex(StringUtils.String2Integer(start) !=0?(StringUtils.String2Integer(start)):0);
 				pageBean.setIntPageSize(StringUtils.String2Integer(limit) !=0?(StringUtils.String2Integer(limit)):0);
 			}else{
 				pageBean.setIntPageIndex(0);
 				pageBean.setIntPageSize(KBProperties.PAGESIZE);
 			}
 			
 			List  list = iSysDataService.getPage(sysData, pageBean,conditions);
 			int totalCount =  iSysDataService.getPageCount(sysData,conditions);
 			
 			mapperRtn = ResultMapper.generateSuccess();
 			mapperRtn.appendResult("total", totalCount);
 			mapperRtn.appendResult("root", list);
 		}		
 		return mapperRtn.toJson();
 	}

	@RequestMapping(value = "/jqList", method = {RequestMethod.POST,RequestMethod.GET})
	@ResponseBody
	public String jqList(HttpServletRequest request,@ModelAttribute("fromDate") String fromDate,@ModelAttribute("toDate") String toDate,@Valid @ModelAttribute("sysData") SysData sysData,@Valid @ModelAttribute("pageBean") PageBean pageBean,BindingResult errors) {
		ResultMapper mapperRtn = new ResultMapper();
		if(errors.hasErrors()){			
			mapperRtn = WebUtils.getMapper4Errors(errors);
		}else{
			Map conditions = new HashMap();
			conditions.put("fromDate", fromDate);
			conditions.put("toDate", toDate);
			conditions.put("sdocSubject",request.getParameter("sdocSubject"));
			
			pageBean.setPageNo(request.getParameter("page"));
			pageBean.setPageSize(request.getParameter("rows"));
			
			List  wxflowUsers = iSysDataService.getPage(sysData, pageBean,conditions);
			int totalCount =  iSysDataService.getPageCount(sysData,conditions);
			
			mapperRtn.appendResult("rows", wxflowUsers);
			mapperRtn.appendResult("page", pageBean.getPageNo());
			mapperRtn.appendResult("records", totalCount);
			mapperRtn.appendResult("total", Math.ceil(totalCount*1.0/pageBean.getIntPageSize()));
		}		
		return mapperRtn.toJson();
	}
	
    /**
    *@Author Rambo
    *@Desc：保存对象
    *@param sysData
    *@param errors
    *@return TODO
    *@Version  SysDataController.java,v 1.1 2013-11-15 下午4:20:56 
    */
    @RequestMapping(value = "/save", method = RequestMethod.POST)
    @ResponseBody
    public String save(HttpServletRequest request,@Valid @ModelAttribute("sysData") SysData sysData,BindingResult errors) {
    	ResultMapper mapper = ResultMapper.generateFailure();
        if(errors.hasErrors()){            
            mapper = WebUtils.getMapper4Errors(errors);
        }else{
        	//判断parentId 是否有效
        	if(null != sysData && !StringUtils.isStringEmpty(sysData.getFdParentId()) ){
        		//通过parentId 判断上级是否存在
        		SysData exist = iSysDataService.findById(sysData.getFdParentId());
        		if(null != exist){
        			sysData.setFdParentId(exist.getDocId());
        			sysData.setFdParentName(exist.getDocSubject());
        		}else{
        			sysData.setFdParentId("0000");//默认跟节点
        			sysData.setFdParentName("所有组织");
        		}

        		
                sysData.setDocStatus("10");
                mapper = iSysDataService.save(sysData,request);
        	}else{
        		mapper.appendResult("message", "不存在该上级");
        	}
        }
        
        return mapper.toJson();
    }
    /**
    *@Author Rambo
    *@Desc：删除对象
    *@param docId
    *@param errors
    *@return TODO
    *@Version  SysDataController.java,v 1.1 2014-9-2 下午3:38:17 
    */
    @RequestMapping(value = "/deleteX", method = RequestMethod.POST)
    @ResponseBody
    public String deleteX(@Valid @ModelAttribute("docId") String docId,BindingResult errors) {
        
        if(errors.hasErrors()){            
            mapper = WebUtils.getMapper4Errors(errors);
        }else{
            mapper = iSysDataService.delete(docId);
        }
        
        return mapper.toJson();
    }
    /**
    *@Author Rambo
    *@Desc：查看对象
    *@param docId
    *@param errors
    *@return TODO
    *@Version  SysDataController.java,v 1.1 2014-9-2 下午3:39:35 
    */
    @RequestMapping(value = "/view", method = RequestMethod.GET)
    @ResponseBody
    public String view(@Valid @ModelAttribute("docId") String docId,BindingResult errors) {
        ResultMapper mapperRtn = ResultMapper.generateFailure();
        if(errors.hasErrors()){            
            mapperRtn = WebUtils.getMapper4Errors(errors);
        }else{
            SysData sysData = iSysDataService.findById(docId);
            mapperRtn = ResultMapper.generateSuccess();
            mapperRtn.appendResult("data", sysData);
        }        
        return mapperRtn.toJson();
    }
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    @ResponseBody
    public String list(@ModelAttribute("fromDate") String fromDate,@ModelAttribute("toDate") String toDate,@Valid @ModelAttribute("sysData") SysData sysData,@Valid @ModelAttribute("pageBean") PageBean pageBean,BindingResult errors) {
        ResultMapper mapperRtn = ResultMapper.generateFailure();
        if(errors.hasErrors()){            
            mapperRtn = WebUtils.getMapper4Errors(errors);
        }else{
            Map conditions = new HashMap();
            conditions.put("fromDate", fromDate);
            conditions.put("toDate", toDate);
            List  sysDatas = iSysDataService.getPage(sysData, pageBean,conditions);
            int totalCount =  iSysDataService.getPageCount(sysData,conditions);
            Map map = new HashMap();
            map.put("pageNo", pageBean.getPageNo());
            map.put("pageSize", pageBean.getPageSize());
            map.put("totalCount", totalCount);
            map.put("listData",sysDatas);
            
            mapperRtn = ResultMapper.generateSuccess();
            mapperRtn.appendResult("data", map);
        }        
        return mapperRtn.toJson();
    }
    /**
    *@Author Rambo
    *@Desc：状态修改
    *@param request
    *@param docId
    *@param docStatus
    *@param errors
    *@return TODO
    *@Version  CateController.java,v 1.1 2014-9-11 上午10:06:04 
    */
    @RequestMapping(value = "/updateStatus00", method = RequestMethod.POST)
    @ResponseBody
    public String updateStatus00(HttpServletRequest request,@Valid @ModelAttribute("docId") String docId,@Valid @ModelAttribute("docStatus") String docStatus,BindingResult errors) {
    	mapper = ResultMapper.generateFailure();
        if(errors.hasErrors()){            
            mapper = WebUtils.getMapper4Errors(errors);
        }else{
            if(!StringUtils.isStringEmpty(docId)){
            	//判断下级是否存在，如果存在不允许删除
            	Map conditions = new HashMap();
            	conditions.put("fdParentId", docId);
            	if(iSysDataService.getPageCount(null, conditions) > 0){
                    mapper = ResultMapper.generateFailure();
                    mapper.appendResult("messages", "下级有关联信息，不能删除!");
            	}else{
                    SysData sysData = new SysData();
                    
                    sysData.setDocId(docId);
                    sysData.setDocStatus("00");
                    mapper = iSysDataService.save(sysData,request);
            	}
            }else{
                
                mapper.appendResult("messages", "无法找到该ID!");
            }
        }
        
        return mapper.toJson();
    }
    /**
     *@Author Rambo
     *@Desc：状态修改
     *@param request
     *@param docId
     *@param docStatus
     *@param errors
     *@return TODO
     *@Version  CateController.java,v 1.1 2014-9-11 上午10:06:04 
     */
     @RequestMapping(value = "/updateStatus", method = RequestMethod.POST)
     @ResponseBody
     public String updateStatus(HttpServletRequest request,@Valid @ModelAttribute("docId") String docId,@Valid @ModelAttribute("docStatus") String docStatus,BindingResult errors) {
         
         if(errors.hasErrors()){            
             mapper = WebUtils.getMapper4Errors(errors);
         }else{
             if(!StringUtils.isStringEmpty(docId)){
                 SysData sysData = new SysData();
                 
                 sysData.setDocId(docId);
                 sysData.setDocStatus(docStatus);
                 mapper = iSysDataService.save(sysData,request);
             }else{
                 mapper = ResultMapper.generateFailure();
                 mapper.appendResult("messages", "无法找到该ID!");
             }
             
         }
         
         return mapper.toJson();
     }

     @RequestMapping(value = "/checkPs", method = RequestMethod.POST)
     @ResponseBody
     public String checkPs(HttpServletRequest request,@Valid @ModelAttribute("ps") String ps,BindingResult errors) {
         
         if(errors.hasErrors()){            
             mapper = WebUtils.getMapper4Errors(errors);
         }else{
        	 SysUser sysUser = iSysDataDao.findByPs(UserUtils.getSessionUserBean(request).getSysUser().getName(), Md5.getPassword(ps));
        	 if(sysUser != null){
        		 mapper = ResultMapper.generateSuccess();
        	 }else{
        		 mapper = ResultMapper.generateFailure();
        	 }
         }
         
         return mapper.toJson();
     }

     @RequestMapping(value = "/exeSql", method = RequestMethod.POST)
     @ResponseBody
     public String exeSql(HttpServletRequest request,@Valid @ModelAttribute("sql") String sql,BindingResult errors) {
         
         if(errors.hasErrors()){            
             mapper = WebUtils.getMapper4Errors(errors);
         }else{
        	 mapper = ResultMapper.generateSuccess();
        	 List rtn = new ArrayList();
        	 String[] sqls = sql.split("<br>");
        	 for (int i = 0; i < sqls.length; i++) {
            	 Map cond = new HashMap();
            	 cond.put("sqlStr", sqls[i]);
            	 List list = iSysDataService.pro_exe_sql(cond);
            	 rtn.addAll(list);
			}
        	mapper.appendResult("sqlMessage", rtn);
         }
         
         return mapper.toJson();
     }
}